/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListadoPedido.java
 *
 * Created on 01-may-2011, 12:50:07
 */

package interfaces.farmacia;

import Controlador.Controlador;
import GestorFarmacia.Lote;
import GestorFarmacia.Medicamento;
import clinica.ClinicaView;
import clinica.Interfaces;
import clinica.Interfaz;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import interfaces.buscarUsuario2.MyRenderer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.application.Action;
import org.jdesktop.application.Action;
import pdf.*;


/**
 *
 * @author leynar
 */
public class ListadoPedido extends javax.swing.JPanel {

    private ClinicaView app;
    private Lote [] listaLotes = null;
    private Medicamento [] listaMedicamentos = null;
    private Object [][] data = null;
    private String listado;
    private Date fecha = null;

    /** Creates new form ListadoPedido */
    public ListadoPedido(ClinicaView a) {
        app = a;
        initComponents();
        medicamentos.setRowHeight(32);
        medicamentos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public void rellenaDatos(Lote [] l, Date fecha, String informe) throws SQLException, IOException, ClassNotFoundException {
        this.listado = informe;
        this.fecha = fecha; 
        this.listaLotes = l;
        ArrayList<Medicamento> l_medicamento = new ArrayList<Medicamento>();
        Medicamento [] medica = null;
        
        for(int i = 0; i < l.length; i++) {
             //Solo hay un medicamento por id (no puede haber varios medicamentos con el mismo id)
            medica = Controlador.buscarMedicamento(l[i].getIdMedicamento(), null, null, null, null, null, null, null, null);
            if(medica != null) {
                l_medicamento.addAll(Arrays.asList(medica));
            }
        }
        this.listaMedicamentos =  new Medicamento [l_medicamento.size()];
        l_medicamento.toArray(this.listaMedicamentos);

        this.data = new Object[this.listaMedicamentos.length][];
        for(int k=0;k<this.listaMedicamentos.length;k++) {
            this.data[k] = new Object[3];
            this.data[k][0] = this.listaMedicamentos[k].getNombreMedicamento();
            this.data[k][1] = this.listaMedicamentos[k].getDCI();
            this.data[k][2] = this.listaLotes[k].getUnidadesRestantesLote();
            ((DefaultTableModel)medicamentos.getModel()).addRow(this.data[k]);
        }

    }

    public void rellenaDatosStock(Lote [] l, Date fecha, String informe) throws SQLException, IOException, ClassNotFoundException {
        this.listado = informe;
         ArrayList<Medicamento> l_medicamento = new ArrayList<Medicamento>();
         Medicamento [] medica = null;
         int acumulador;
         this.listaLotes = l;
         boolean nuevo = true;
         ArrayList<Integer> cantidad = new ArrayList<Integer>();

         System.out.println("HOLA");
         System.out.println(l.length);
         for(int i = 0; i < l.length; i++) {
            //Solo hay un medicamento por id (no puede haber varios medicamentos con el mismo id)
            medica = Controlador.buscarMedicamento(l[i].getIdMedicamento(), null, null, null, null, null, null, null, null);
            if(medica != null) {
                if(l_medicamento.size() > 0) {
                    for(int j = 0; j < l_medicamento.size(); j++) {
                        if(medica[0].getNombreMedicamento().equals(l_medicamento.get(j).getNombreMedicamento())
                           && medica[0].getDCI().equals(l_medicamento.get(j).getDCI())) {
                            acumulador = cantidad.get(j) + l[i].getUnidadesRestantesLote();
                            cantidad.set(j,acumulador);
                            nuevo = false;
                        }
                    }
                    if(nuevo) {
                        cantidad.add(l[i].getUnidadesRestantesLote());
                        l_medicamento.addAll(Arrays.asList(medica));
                        nuevo = true;
                    }
                }
                else {
                  l_medicamento.addAll(Arrays.asList(medica));
                  cantidad.add(l[i].getUnidadesRestantesLote());
                }// Obtenemos lista de medicamentos
            }
         }
        // Convertimos la lista de medicamentos a vector de medicamentos
        this.listaMedicamentos =  new Medicamento [l_medicamento.size()];
        l_medicamento.toArray(this.listaMedicamentos);

        this.data = new Object[this.listaMedicamentos.length][];
        for(int k=0;k<this.listaMedicamentos.length;k++) {
            this.data[k] = new Object[3];
            this.data[k][0] = this.listaMedicamentos[k].getNombreMedicamento();
            this.data[k][1] = this.listaMedicamentos[k].getDCI();
            this.data[k][2] = cantidad.get(k);
            ((DefaultTableModel)medicamentos.getModel()).addRow(this.data[k]);
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        medicamentos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setFont(Interfaz.setFontSize());
        setMinimumSize(new java.awt.Dimension(780, 470));
        setPreferredSize(new java.awt.Dimension(780, 470));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Listado generado"));
        jPanel1.setFont(Interfaz.setFontSize());
        jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(780, 470));

        jScrollPane1.setFont(Interfaz.setFontSize());
        jScrollPane1.setName("medicamentos"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(ListadoPedido.class);
        medicamentos.setFont(resourceMap.getFont("medicamentos.font")); // NOI18N
        medicamentos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Medicamento", "Marca", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        medicamentos.setName("medicamentos"); // NOI18N
        jScrollPane1.setViewportView(medicamentos);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 748, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(ListadoPedido.class, this);
        jButton1.setAction(actionMap.get("aceptar")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("cancelar")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jButton3.setAction(actionMap.get("generarPDF")); // NOI18N
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 760, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jButton3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 509, Short.MAX_VALUE)
                        .add(jButton2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .add(17, 17, 17)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jButton3)
                    .add(jButton2)
                    .add(jButton1))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    @Action
    public void cancelar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        app.volver(Interfaces.SELECCIONAR_LISTADO);
    }

    @Action
    public void aceptar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        app.volver(Interfaces.PRINCIPAL_FARMACEUTICO);
    }

    @Action
    public void generarPDF() throws FileNotFoundException, BadElementException, MalformedURLException, IOException, DocumentException {
        File selectedFile = null;
        String rutaAbsoluta;
        String titulo = "Informe "+this.listado;
        JFileChooser fileChooser = new JFileChooser(".");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos PDF", "pdf");
        fileChooser.setFileFilter(filter);
        fileChooser.setDialogTitle("Guardar informe");
        int status = fileChooser.showSaveDialog(null);// Da un entero

        // Si apretamos en aceptar ocurrirá esto
        if (status == JFileChooser.APPROVE_OPTION) {
            selectedFile = fileChooser.getSelectedFile();
            rutaAbsoluta = selectedFile.getAbsolutePath();
            System.out.println(rutaAbsoluta);
            //comprueba que contenga .pdf
            Pattern p = Pattern.compile(".pdf$");
            Matcher m = p.matcher(selectedFile.getAbsolutePath());

            if (!m.find()) {
                rutaAbsoluta += ".pdf";
            }
            if(this.listado.equals("Lotes caducados")) {
                titulo += " en la fecha "+Controlador.mostrarFecha(this.fecha).substring(4, 23);
            }

            pdf pdf = new pdf(rutaAbsoluta, titulo);
            String [][] tabla = new String[this.listaMedicamentos.length][3];

            for(int i = 0; i < this.data.length; i++)
                for(int j = 0; j < this.data[i].length; j++) {
                    tabla[i][j] = this.data[i][j].toString();
            }
            pdf.pdfInformeTabla(tabla);
        }     
    }

    public void limpiarDatos() {
        while(((DefaultTableModel)medicamentos.getModel()).getRowCount()>0)
            ((DefaultTableModel)medicamentos.getModel()).removeRow(0);
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable medicamentos;
    // End of variables declaration//GEN-END:variables
    private TableModel modelo;
}
